<template>
    <div style="display: flex">
        <el-button type="primary" style="margin-right: 15px" @click="addItem">新增</el-button>
        <el-input v-model="searchCourseName" placeholder="请输入课程名称"
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" clearable></el-input>
        <el-select v-model="searchCourseType" placeholder="课程分类" filterable clearable
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px">
            <el-option v-for="item in courseTypeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
        </el-button>
    </div>

    <!-- 课程表格 -->
    <el-table :data="tableData" :row-style="{ height: '77px' }" border
        style="width: calc(100vw - 240px);height: 75vh;margin-top: 20px;font-size: 15px;">
        <el-table-column align="center" prop="id" label="课程ID" width="150" />
        <el-table-column align="center" prop="name" label="课程名称" width="200" />
        <el-table-column align="center" prop="courseTypeName" label="课程类型" width="auto" />
        <el-table-column align="center" prop="createTime" label="创建时间" width="auto" />
        <el-table-column align="center" fixed="right" label="操作" width="200">
            <template v-slot="scope">
                <div>
                    <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
                    <el-button type="warning" size="small" icon="View" @click="toStuFeedback(scope.row.id)">反馈
                    </el-button>
                </div>
                <div>
                    <el-button type="success" size="small" icon="View" @click="toPeriodDetail(scope.row.id)">视频
                    </el-button>
                    <el-button type="success" size="small" icon="View" @click="toTeachPlanDetail(scope.row.id)">资料
                    </el-button>
                </div>
                <div>
                    <el-button type="success" size="small" icon="View" @click="toLessonNoteDetail(scope.row.id)">教案
                    </el-button>
                    <el-button type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px">
        <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :background="true"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
    </div>

    <!-- 添加课程对话框 -->
    <el-dialog v-model="dialogVisible" title="课程操作" width="560">
        <el-form label-position="top" :inline="true" :model="form" ref="form" :rules="rules">
            <el-form-item label="课程名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入课程名称" clearable></el-input>
            </el-form-item>

            <el-form-item label="课程分类" prop="courseTypeId" style="width: 185px">
                <el-select v-model="form.courseTypeId" placeholder="请选择课程分类" filterable clearable>
                    <el-option v-for="item in courseTypeOptions" :key="item.id" :label="item.name"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="课程图片" prop="url">
                <el-upload
                        class="avatar-uploader"
                        :before-upload="checkFileType"
                        :action="'/api/files/upload'"
                        :on-success="photoHandleSuccess"
                        :on-error="photoHandleError"
                        :show-file-list="false"
                >
                    <img width="100" height="100" v-if="form.url" :src="form.url" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item label="上传资料" style="width:100%">
                <el-upload
                        :before-upload="checkFileType"
                        :action="'/api/files/uploadSign'"
                        :file-list="form.teachPlans"
                        :on-success="fileUrlUploadSuccess"
                        :on-remove="fileUrlRemove"
                        drag
                        multiple
                        style="width:92%"
                >
                    <el-icon class="el-icon--upload">
                        <upload-filled/>
                    </el-icon>
                    <div class="el-upload__text">
                        拖拽或<em>点击</em>上传
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            请上传PDF/DOC/PPT等文档文件
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset('form')">取消</el-button>
                <el-button type="primary" @click="submitForm('form')">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>

    import {ref} from 'vue'
    import request from "~/utils/request.js";

export default {
    data() {
        return {
            dialogVisible: false,
            tableData: [],
            form: {
                name: '',
                courseTypeId: '',
                teachPlans: []
            },
            courseTypeOptions: [],
            searchCourseName: '',
            searchCourseType: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            rules: {
                name: [
                    { required: true, message: '请输入课程名称', trigger: 'blur' },
                ],
                courseTypeId: [
                    { required: true, message: '请选择课程分类', trigger: 'blur' },
                ]
            }
        }
    },
    async created() {
        await this.getCourseTypeOptions()
        await this.load()
    },
    methods: {
        async load() {
            if (this.searchCourseType === undefined) {
                this.searchCourseType = ''
            }
            request.get("/course/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&name=" + this.searchCourseName + "&typeId=" + this.searchCourseType).then(res => {
                if (res.code === '200') {
                    this.tableData = res.data.records;
                    this.total = res.data.total;
                } else {
                    ElMessage.error("错误" + res.msg)
                }
            })
        },
        async getCourseTypeOptions() {
            request.get("/course-type/all").then(res => {
                this.courseTypeOptions = res.data
            })
        },
        toPeriodDetail(scope) {
            this.$router.push({ path: "/file/videoList", query: { courseId: scope } });
        },
        toTeachPlanDetail(scope) {
            this.$router.push({ path: "/file/filesList", query: { courseId: scope } });
        },
        toLessonNoteDetail(scope) {
            this.$router.push({ path: "/file/lessonNoteList", query: { courseId: scope } });
        },
        toStuFeedback(scope) {
            this.$router.push({ path: "/course/stuFeedbackList", query: { courseId: scope } });
        },
        editItem(item) {
            Object.assign(this.form, item)
            this.form.teachPlans = this.form.teachPlans || [];
            request.get("/teach-plan/findByCourseId?courseId=" + this.form.id).then(res => {
                if (res.code === '200' && res.data.length > 0) {
                    for (let i = 0; i < res.data.length; i++) {
                        this.form.teachPlans.push(res.data[i])
                    }
                }
            })
            this.dialogVisible = true
        },
        addItem() {
            this.dialogVisible = true;
        },
        // 删除
        deleteItem(scope) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/course/delete/" + scope).then(res => {
                    if (res.code === '200') {
                        this.$message.success("成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            });
        },
        photoHandleSuccess(response) {
            this.form.url = `/api/file/download/${response}`
            this.$message.success('上传成功');
        },
        photoHandleError() {
            this.$message.error("上传文件失败")
        },
        // 提交
        submitForm(val) {
            this.$refs[val].validate((valid) => {
                if (valid) {
                    console.log('Request data:', this.form.teachPlans);
                    request.post("/course/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: "成功",
                                type: "success"
                            })
                            this.load()
                            this.reset(val)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },
        checkFileType(file) {
            const maxSize = 1024 * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.warning('文件大小超过1GB限制!');
                return false;
            }
            return true;
        },
        fileUrlUploadSuccess(response) {
            if (response.code != '200') {
                return;
            }
            this.form.teachPlans.push(response.data);
            this.$message.success('上传成功');
        }, //上传成功钩子
        fileUrlRemove(uploadFile) {
            if (!uploadFile.id) {
                return;
            }
            request.get("/teach-plan/delete/" + uploadFile.id).then(res => {
                if (res.code != '200') {
                    return;
                }
                if (res.data.toString() == "true") {
                    this.form.teachPlans = this.form.teachPlans.filter((file) => file.id !== uploadFile.id);
                    this.$message.success('删除成功');
                } else {
                    this.$message.error('删除失败');
                }
            })
        }, //删除成功钩子
        // 取消
        reset(val) {
            this.dialogVisible = false;
            this.form = { name: '', courseTypeId: '', teachPlans: [] };
            this.$refs[val].resetFields();
        },
        handleCurrentChange(item) {
            // 改变当前页码触发
            this.currentPage = item
            this.load()
        },
        handleSizeChange(item) {   // 改变当前每页的个数触发
            this.pageSize = item
            this.load()
        },
    }
}
</script>

<style scoped>
</style>
